//
//  YYTNetEngine.swift
//  Yuyuto
//
//  Created by Arthur on 2017/6/19.
//  Copyright © 2017年 yuyuto. All rights reserved.
//
import Foundation
import UIKit
import SwiftyJSON
import Alamofire


public enum YYTResErrorDomain: String {
    case server = "YYTResErrorDomainServer" // 服务器返回的错误，比如参数教研失败等
    case app = "YYTResErrorDomainApp" // app抛出的错误，比如断网等
}

public enum YYTResponseResult<Value> {
    case Error(NSError)
    case Value(Value)
    
    init(_ e: NSError?, _ v: Value) {
        if let ex = e {
            self = YYTResponseResult.Error(ex)
        } else {
            self = YYTResponseResult.Value(v)
        }
    }
}

class YYTNetEngine: NSObject {
    public var hostUrl: String
    static let sharedInstance = YYTNetEngine()
    var httpHeader:HTTPHeaders = {
//        let deviceInfo = "empty device info"//RNDeviceInfo.init();
        var userAgent:String = SessionManager.defaultHTTPHeaders["User-Agent"]!;
//        userAgent = deviceInfo.requestUserAgent()
        let header = ["User-Agent":userAgent];
        return header;
    }()
    
    private override init() {
        var appConfig = Configuration()
        hostUrl = appConfig.enviroment.host as String
        SessionManager.default.session.configuration.timeoutIntervalForRequest = 10;
        super.init()
    }

    public func post(parameters:[String: Any], resourcePath:String?, completionHandler:@escaping (_ result :YYTResponseResult<JSON>)->Void) {

        let path = resourcePath ?? "";
        let fullUrl = self.hostUrl + path;
        

        
        Alamofire.request(fullUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default,headers:self.httpHeader)
            .downloadProgress(queue: DispatchQueue.global(qos:.utility)) { (progress) in
            }
            
            .validate { request, response, data in
                return .success
            }
            
            .responseJSON { response in
                switch response.result {
                case .success(let value):
                    let json = JSON(value)
//                    completionHandler(YYTResponseResult.Value(json))
                    completionHandler(self._responseHandler(json: json));
                case .failure(let error):
                    completionHandler(YYTResponseResult.Error(error as NSError))

                }
                
        }
    }
    
    public func postWithResponse(parameters:[String: Any], resourcePath:String?, completionHandler:@escaping (_ result :YYTResponseResult<JSON>,_ response:HTTPURLResponse?)->Void) {
        
        let path = resourcePath ?? "";
        let fullUrl = self.hostUrl + path;
        
        Alamofire.request(fullUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default,headers:self.httpHeader)
            
            .downloadProgress(queue: DispatchQueue.global(qos:.utility)) { (progress) in
                print("progress : \(progress.fractionCompleted)");
            }
            
            .validate { request, response, data in
                return .success
            }
            
            .responseJSON { response in
                switch response.result {
                case .success(let value):
                    let json = JSON(value)
                    completionHandler(self._responseHandler(json: json), response.response);
                case .failure(let error):
                    completionHandler(YYTResponseResult.Error(error as NSError), response.response)
                    
                }
                
        }
    }

    private func _responseHandler(json:JSON) -> YYTResponseResult<JSON> {
        if let code:Int = json["code"].int {
            if code == 10000 {
                // 成功
                 if let data:Any =  json["data"] {
                    return YYTResponseResult.Value(data as! JSON);
                 } else {
                    return YYTResponseResult.Value(JSON.null)
                 }
            } else {
                // 接口级的错误
                let errorMsg:String = json["msg"].string ?? "服务器错误";
                
                let userInfo: [AnyHashable : Any] = [
                    NSLocalizedDescriptionKey :  errorMsg,
                    NSLocalizedFailureReasonErrorKey : errorMsg];
                return YYTResponseResult.Error(NSError(domain: YYTResErrorDomain.server.rawValue, code: code, userInfo:userInfo as? [String : Any]))
                
            }
        } else {
            // 系统级的网络错误
            let userInfo: [AnyHashable : Any] = [
                NSLocalizedDescriptionKey :  "服务器未返回Code",
                NSLocalizedFailureReasonErrorKey : "服务器未返回Code"];
            return YYTResponseResult.Error(NSError(domain: YYTResErrorDomain.app.rawValue, code: -1, userInfo:userInfo as? [String : Any]))
        }
 
    }

}
